// 1初始化
layui.use(['form','layer','laydate','table','element'],function(){
    var $ = layui.jquery;
    var form = layui.form;
    var table= layui.table;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var element = layui.element;
    var schoolData = null;//xql 学校数据用于填充学校下拉框，防止反复从服务器下载学校数据
    var tBuildData = null;

	var navList = null;

	var schoolId_v ='';
	var tBuildName_v ='' ;
     //xql 2显示列表
     var tableIns = table.render({
         elem: '#list',
		 url : '/classroom/queryAllClassRoom?buildName=' +tBuildName_v+'&schoolID=' + schoolId_v, //模糊查询
         cellMinWidth : 95,
         page : true,
         width : 700,
         height : 670,
         limit : 15,
         limits : [15,10,20,30],
         id : "listTable",
         method:'post',
         cols : [[
			 {field: 'tbuildid', title: '教学楼ID', width:150,align:'center'},
             {field: 'classroom', title: '教室名称', width:100,align:'center'},
			 {field: 'classroomid', title: '教室ID', width:150,align:'center'},
             {field: 'addtime', title: '添加时间', width:180, align:'center'},
             {fixed:"right",title: '操作', toolbar:'#listRowBar',align:"center"}
         ]]
     });


     //xql 3操作 2)新增 (a)打开添加的弹出层
    $(".add_btn").click(function(){
        mainIndex = layer.open({
            title : ['添加教室','font-size:18px;text-align:center;color:blue;'],
            type : 1, // 0.默认信息框,1.page,2.iframe,3.加载层,4.tips层
            content : $("#addDiv"),// ,$("#addDiv"),type:1 | "gatewayAdd.html", type:2
            area:['400px','280px'],
            offset:'r',
            success : function(){
                if(schoolData == null) {
                    $.ajax({ // 从后台获取学校数据，填充前端的学校下拉框
                        url:'/school/getAllSchoolName',
                        dataType:'json',
                        type:'post',
                        success:function(data2){
                            schoolData = data2;
                            $.each(data2,function(index,item){
                                $("#schoolId").append(new Option(item.name,item.id));
                            });
                            form.render("select");

                        }
                    })
                }else{
                    $.each(schoolData,function(index,item){
                        $("#schoolId").append(new Option(item.name,item.id));
                    });
                    form.render("select");
                }
            }
        })
    });
	//yw 改变学校下拉框的选项，填充教学楼下拉框 lay-filter="schoolId2"
	form.on("select(schoolId)",function(){
	    $.ajax({ //yw 从后台获取教学楼数据，填充前端的教学楼下拉框
	        url:'/school/getAlltBuildNameID?schoolID='+$("#schoolId").val(),
	        async:false, 
	        dataType:'json',
	        type:'post',
	        success:function(res){
	            tBuildData = res;
	            $("#tbuildName").empty();
	            $.each(tBuildData,function(index,item){
	                $("#tbuildName").append(new Option(item.tbuildname,item.tbuildid));
	            }); 
	            form.render("select");           
	        }
	    })
	});
    //xql 3操作 2)新增 (b)提交监听事件--新增记录
    form.on("submit(doSubmitAdd)",function(){
        $.ajax({
            type:"post",
            url:"/classroom/addClassRoom",
            //data:{tbuildid:$("#tbuildid").val(),classroomid:$("#classroomid").val(),classroom:$("#classroom").val()},
            data:{tbuildid:$("#tbuildName").val(),classroom:$("#classroom").val()},
			success:function(res){
                if(res == 1){
                    tableIns.reload();
                    layer.msg('新增成功',{icon:7,time:800,shade:[0.6,'#000',true]});
					layer.closeAll('page'); // 关闭新增界面
					tableIns.reload();
				}else if(res == 2){
					layer.msg('教室id重复，请更换！',{icon:7,time:800,shade:[0.6,'#000',true]});
				}else{
                    layer.msg('新增失败',{icon:7,time:800,shade:[0.6,'#000',true]});
                }
            }
        });
    });

    //xql 监听行工具条的事件
    table.on("tool(list)", function(obj){
        var   data = obj.data; //获得当前行数据
        switch(obj.event){
            case 'edit':
                openUpdateLayer(data);
                break;
            case 'del':
                deleteInfo(data);
                break;
        };
    });
    //xql 监听导航事件
    $("[name=t1]").click(function (){

		//var navList2 = null;
        //var name_v = $(".searchVal").val().trim();
		var name_v = "";


		schoolId_v =  $(this).attr("schoolId");
		tBuildName_v =  $(this).attr("tBuildName");
		tBuildID =  $(this).attr("tBuildID");
		//schoolId_v = navList2[schoolId_v].p;
		//alert(schoolId_v+"---"+tBuildName_v+"----"+tBuildID);
        var url_address = '/classroom/queryClassRoomById?&buildID='+tBuildID;
        if(name_v!=""){
            url_address = url_address+'&name='+name_v;
        }
        tableIns.reload({
            page: {
                    curr: 1 //重新从第 1 页开始
            },
            url : url_address, //模糊查询
        });
        return false;
    });
    //yw 3操作 3)更新  (a)打开修改的弹出层
    function openUpdateLayer(data){

        mainIndex = layer.open({
            title : ['修改教室信息','font-size:18px;text-align:center;color:blue;'],
            type : 1,
            content : $("#saveDiv"),
            area:['400px','300px'],
            offset:'r',
            success:function(layero,index){ //yw layero是弹出层对象layer object
                if(schoolData == null) {
                    $.ajax({ // 从后台获取学校数据，填充前端的学校下拉框
                        url:'/school/getAllSchoolName',
                        async:false, //yw 取消异步下载模式，否则shoolId2第一次打开没有数据，第二次打开才有数据
                        dataType:'json',
                        type:'post',
                        success:function(res){
                            schoolData = res;
                            $.each(schoolData,function(index,item){
                                $("#schoolId2").append(new Option(item.name,item.id));
                            });
                        }
                    })
                }else{
                    $.each(schoolData,function(index,item){
                        $("#schoolId2").append(new Option(item.name,item.id));
                    });
                }
				 $("#tbuild2").val(data.tbuildid);
				 $("#classroom3").val(data.classroomid);
				 $("#classroom2").val(data.classroom);

                 if(tBuildData == null){
                    $.ajax({ // 从后台获取教学楼数据，填充前端的教学楼下拉框
                        url:'/school/getAlltBuildName?schoolID='+$("#schoolId2").val(),
                        async:false,
                        dataType:'json',
                        type:'post',
                        success:function(res2){
                            tBuildData = res2;
                            $("#tbuildName").empty();
                            $.each(res2,function(index,item){

                                $("#tbuildName").append(new Option(item,item));
                            });
                        }
                    })
                }else{
                    $("#tbuildName").empty();
                    $.each(tBuildData,function(index,item){
                        $("#tbuildName").append(new Option(item,item));
                    });
                }
                $("#tbuildName").val(data.tbuildname);
                form.render("select");
                 $("#authcroomid").val(data.authcroomid);
                 $("#userState").val(data.userstate);
                 $("#post").val(data.post);
                 $("#userRemark2").val(data.userremark);
            }
        });
     }
     //xql 改变学校下拉框的选项，填充教学楼下拉框 lay-filter="schoolId2"
     form.on("select(schoolId2)",function(){
        $.ajax({ //yw 从后台获取教学楼数据，填充前端的教学楼下拉框
            url:'/school/getAlltBuildName?schoolID='+$("#schoolId2").val(),
            async:false,
            dataType:'json',
            type:'post',
            success:function(res){
               tBuildData = res;
               //console.log(tBuildData);
               $("#tbuildName").empty();
               $.each(tBuildData,function(index,item){
                   $("#tbuildName").append(new Option(item,item));
               });
               form.render("select");
            }
        })
     });
         // 3操作 3)更新 (b)提交监听事件--修改记录
    form.on("submit(doSubmitSave)",function(){
        $.ajax({
            type:"post",
            url:"/classroom/save",
            data:{classroomid:$("#classroom3").val(),classroom:$("#classroom2").val()},
            success:function(res){
                if(res){
                    tableIns.reload();
                    layer.msg('保存成功',{icon:7,time:800,shade:[0.6,'#000',true]});
                }else{
                    layer.msg('保存失败',{icon:7,time:800,shade:[0.6,'#000',true]});
                }
                layer.closeAll('page'); //yw 关闭新增界面 type=1
            }
        });
        return false;
    });
    //xql 3操作 4)删除
    function deleteInfo(data){
        layer.confirm('你确定要删除这条数据吗?',{icon:3,title:'提示'},function(index){
            $.ajax({
                type:"POST",
                url:'/classroom/defClassRoom?classroomID='+data.classroomid,
                success:function(res){
                    if(res){
                        tableIns.reload();
                        layer.msg('删除成功',{icon:7,time:800,shade:[0.6,'#000',true]});
                    }else{
                        layer.msg('删除失败',{icon:7,time:800,shade:[0.6,'#000',true]});
                    }
                }
            });
            layer.close(index); //xql 关闭删除提示对话框
        });
    }

    //yw 表单验证
    form.verify({
        required: [/[\S]+/, "不能为空"],
        username:[/^[a-zA-Z0-9_-]{4,16}$/,"用户名4-16位字母数字下划线减号"],
        phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
        email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
        url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
        integer: [/^\d*$/, "只能填写整数"],
        date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
        identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"],
        // 校验两次密码是否一致
        userPwd: [/(.+){6,12}$/, '密码必须6到12位'],
        userPwdCheck:function(value){
            if($('input[name=userPwd]').val() !== value)
                return '两次密码输入不一致！';
        },
        number: function (e) {
            if (e && isNaN(e))return "只能填写数字"
        },
        lenLimit20:function(value){
            if(value.length>20) return '长度不能超过20个字符';
        },
        lenLimit50:function(value){
            if(value.length>20) return '长度不能超过50个字符';
        },
        lenLimit100:function(value){
            if(value.length>100) return '长度不能超过50个字符';
        }
    });
    //导航

});
